package com.roin.learn.redis.service.impl;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.roin.learn.redis.dao.UserMapper;
import com.roin.learn.redis.entity.User;
import com.roin.learn.redis.entity.UserExample;
import com.roin.learn.redis.service.UserService;

@Service
public class UserServiceImpl implements UserService{
	@Autowired
	private UserMapper userMapper;

	@Cacheable(value="user",keyGenerator="customKeyGenerator")
	public User getById(String userId) {
		return userMapper.selectByPrimaryKey(userId);
		
	}
	
	
	@Cacheable(value="user",keyGenerator="customKeyGenerator")
	//value值是必须指定的，其表示该方法缓存的返回结果是被缓存在哪个Cache上的，对应Cache的名称。
	//key属性是用来指定Spring缓存方法返回结果时所对应的key值的。该属性支持EL表达式。当我们没有指定key时，Spring会使用默认策略生成key。
	//keyGenerator属性用来指定使用具体的key生成策略，这里使用了自定的customKeyGenerator，在com.roin.learn.redis.cache.RedisCacheConfig里定义了这个bean
	@Override
	public List<User> getAll() {
		return userMapper.selectByExample(new UserExample());
	}
	@Cacheable(value="user",keyGenerator="customKeyGenerator")
	@Override
	public List<User> getPage(int pageNo,int pageSize) {
		UserExample example = new UserExample();
		example.setLimit(pageSize);
		example.setOffset((pageNo-1)*pageSize);
		return userMapper.selectByExample(example);
	}

	@Cacheable(value="user",keyGenerator="customKeyGenerator")
	@Override
	public int count() {
		return userMapper.countByExample(new UserExample());
	}
	
	@CacheEvict(value = "user", allEntries = true)
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	@Override
	public int update(User user) {
		return userMapper.updateByPrimaryKeySelective(user);
	}
	@CacheEvict(value = { "user" }, allEntries = true)
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	@Override
	public String save(User user) {
		if (user!=null) {
			user.setUserId(UUID.randomUUID().toString());
			userMapper.insert(user);
			return user.getUserId();
		}
		return null;
	}


	@CacheEvict(value = { "user" }, allEntries = true)  
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	@Override
	public boolean delete(User user) {
		if (user!=null && user.getUserId()!=null) {
			return deleteById(user.getUserId());
		}
		return false;
	}
	@CacheEvict(value = { "user" }, allEntries = true)
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	@Override
	public boolean deleteById(String userId) {
		if (userId!=null) {
			int row = userMapper.deleteByPrimaryKey(userId);
			return row>0;
		}
		return false;
	}

}
